%%% File    : gate_sup.erl
%%% Author  :  <>
%%% Description : 
%%% Created : 23 Mar 2011 by  <>
%%one machine can only start a net_server
-module(cache_sup).

-export([start_link/0]).

-export([start_cache/1, stop_cache/1, add_extra/1, del_extra/1]).

-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
	terminate/2, code_change/3]).

-define(SERVER, ?MODULE).

-record(state, {type,
	       cache,
	       restart,
	       extra}).

%%-----------
start_cache(Node) when is_atom(Node) ->
    gen_server:call({global,?SERVER}, {start_cache, Node});
start_cache(_) ->
    {error, badargs}.

stop_cache(Node) when is_atom(Node) ->
    gen_server:call({global,?SERVER}, {stop_cache, Node});
stop_cache(_) ->
    {error, badargs}.
  
add_extra(Node) when is_atom(Node) ->
    gen_server:call({global,?SERVER}, {add_extra, Node});    
add_extra(_) ->
    {error, badargs}.

del_extra(Node) when is_atom(Node) ->
    gen_server:call({global,?SERVER}, {del_extra, Node}); 
del_extra(_) ->
    {error, badargs}.

start_link() ->
    gen_server:start_link({global,?SERVER}, ?MODULE, [], []).

%%--------
init([]) ->
    process_flag(trap_exit, true),
    S = #state{type=cache,
	      cache=[],  %%%[node, pid]
	      restart=3,
	      extra=[]},
    {ok, S}.

handle_call({add_extra, Node}, _From ,S=#state{extra=Ex}) ->
    case lists:member(Node, Ex) of
	true ->
	    {reply, {error, exist}, S};
	false ->
	    {reply, ok, S#state{extra=[Node, Ex]}}
    end;

handle_call({del_extra, Node}, _From, S=#state{extra=Ex}) ->
    case lists:member(Node, Ex) of
	true ->
	    {reply, ok, S#state{extra=lists:delete(Node, Ex)}};
	false ->
	    {reply, {error, noexist}, S}
    end;	
    
handle_call({start_cache, Node}, _From, S) ->
    {Res, Ns} = do_start(Node, S),
    {reply, Res, Ns};

handle_call({stop_cache, Node}, _From, S) ->
    {Res, Ns} = do_stop(Node, S),
    {reply, Res, Ns};

    
handle_call(_Req, _From, S) ->
    {reply, ok, S}.

handle_cast({redirect, Node, Pid}, S=#state{cache=Cache}) ->
    link(Pid),
    {noreply, S#state{cache=[{Node, Pid}|Cache]}};

handle_cast(_Msg, S) ->
    {noreply, S}.

handle_info({'EXIT', _, normal}, S) ->
    {noreply, S};

handle_info({'EXIT', Pid, _}, S=#state{cache=Cache}) ->
    case lists:keysearch(Pid, 2, Cache) of
	false ->
	    {noreply, S};
	{value, {Node, Pid}} ->
	    Ns = do_restart(Node, S),
	    {noreply, Ns}
    end;

handle_info(_Info, S) ->
    {noreply, S}.

terminate(_Reason, _S) -> 
    ok.

code_change(_Oldvsn, S, _Extra) ->
    {ok, S}.

%%-----------
do_start(Node, S=#state{cache=Cache}) ->
    case lists:keymember(Node, 1, Cache) of
	true ->
	    {{error, exist}, S};
	false ->
	    Res = rpc:call(Node, cache_server, start, [self()]),
	    case Res of
		{ok, Pid} ->
		    link(Pid),
		    {ok, S#state{cache=[{Node, Pid}|Cache]}};
		Err ->
		    {{error, Err}, S}
            end
    end.

do_stop(Node, S=#state{cache=Cache}) ->
    case lists:keysearch(Node, 1, Cache) of
	false ->
	    {{error, noexist}, S};
	{value, {Node, Pid}} ->
	    do_exit(Pid),
	    {ok, S#state{cache=lists:keydelete(Node, 1, Cache)}}
    end.

do_exit(Pid) ->
    gen_server:cast(Pid, {do_exit,self()}),
    ok.

do_restart(Node, S=#state{restart=Restart}) ->
    do_restart(Node, S, Restart).

do_restart(Node, S=#state{extra=Extra}, 0) ->
    start_one_extra(Extra, S, Node);
do_restart(Node, S=#state{cache=Cache}, Restart) ->
    Res = rpc:call(Node, cache_server, start, [self()]),
    case Res of
	{ok, Pid} ->
	    link(Pid),
	    S#state{cache=[{Node, Pid}|lists:keydelete(Node, 1, Cache)]};
	_ERR ->
	    do_restart(Node, S, Restart-1)
    end.

start_one_extra([], S=#state{cache=Cache}, Node) ->
    S#state{cache=lists:keydelete(Node, 1, Cache)};
start_one_extra([Hnode|T], S=#state{cache=Cache,extra=Extra}, Node) ->
    Res = rpc:call(Hnode, cache_server, start, [self()]),
    case Res of
	{ok, Pid} ->
	    link(Pid),
	    S#state{cache=[{Hnode, Pid}|lists:keydelete(Node, 1, Cache)],
		   extra=lists:delete(Hnode, Extra)};
	_Err ->
	    start_one_extra(T, S#state{extra=lists:keydelete(Node, 1, Extra)}, Node)
    end.
